//
//  EntertainmentDetailViewController.m
//  PeopleStreet
//
//  Created by 喻飞 on 16/5/7.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "EntertainmentDetailViewController.h"
#import "MovieCommentTableViewCell.h"
#import "FoodsStoreTableViewCell.h"
#import "CommitStarsView.h"
#import "AllMovieCommentViewController.h"
#import "PhotosViewController.h"
#import "PaperListViewController.h"
#import "ForSalePaperViewController.h"
#import "SharePopView.h"
static NSString *CellIdentify = @"FoodsStoreTableViewCell";
static NSString *cellIdentify = @"MovieCommentTableViewCell";
@interface EntertainmentDetailViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITableView *foodsTableView;
@property (strong, nonatomic) IBOutlet UITableView *commentTableView;
@property (strong, nonatomic) IBOutlet UIView *storeInfoView;
@property (strong, nonatomic) IBOutlet UIView *pricePaperView;
@property (strong, nonatomic) IBOutlet UIImageView *storeLogoImage;//商家图片
@property (strong, nonatomic) IBOutlet UIImageView *storeBackImage;//商家图片
@property (strong, nonatomic) IBOutlet UILabel *storeName;//商家名字
@property (strong, nonatomic) IBOutlet UILabel *storeScore;//商家评分
@property (strong, nonatomic) IBOutlet UILabel *storeIntroduce;//商家简介


@property (strong, nonatomic) IBOutlet UILabel *workTime;//营业时间
@property (strong, nonatomic) IBOutlet UILabel *storeAddress;//商家地址
@property (strong, nonatomic) IBOutlet UILabel *storePhone;//商家电话


@property (strong, nonatomic) IBOutlet UILabel *storeForSale;//商家优惠
@property (strong, nonatomic) IBOutlet UILabel *storePrice;//商家价格
@property (strong, nonatomic) IBOutlet UILabel *hadSale;//已售


@property (strong, nonatomic) IBOutlet UILabel *commentScore;//评论分数
@property (weak, nonatomic) IBOutlet UILabel *commentTotalNum;//【评论总数

@property (strong, nonatomic) IBOutlet UILabel *imageNumberBackView;
@property (strong, nonatomic) IBOutlet UILabel *imageNumber;
@property(nonatomic,strong)NSArray * imageArray;
@property (weak, nonatomic) IBOutlet UILabel *commentLineLabel;//评论分割线
@property (weak, nonatomic) IBOutlet UIButton *gotoCmmentPageButton;

@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;

@property(nonatomic,strong)NSMutableArray * groupShops;
@property(nonatomic,strong)NSArray * pricePaperArray;

@end

@implementation EntertainmentDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageArray = [NSArray array];
    _pricePaperArray = [NSArray array];
    _heightArray = [NSMutableArray array];
    _commitArray = [NSMutableArray array];
    _groupShops = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self initViewLayout];
    [self getStoreInfo];
    [self getStoreSalePaper];
    [self getComments];
    [self getStoreGroupIndent];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.storeInfoView];
    [self adaptiveViewLayout:self.pricePaperView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 757), NO);
    
    
    _imageNumberBackView.layer.cornerRadius = 2*VerticalRatio();
    
    
    //注册
    [self.commentTableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];
    
    
    [self.foodsTableView registerNib:[UINib nibWithNibName:CellIdentify bundle:nil] forCellReuseIdentifier:CellIdentify];
    _foodsTableView.scrollEnabled = NO;
    
    
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark == 店铺详情
- (void)getStoreInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_foodId forKey:@"storeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppBusinessDetailsInfo withHttpType:@"POST" withTag:SX_SX_queryAppBusinessDetailsInfo];
    
}

#pragma mark == 店铺团购项目
- (void)getStoreGroupIndent{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    [dic setObject:_foodId forKey:@"storeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGrouponProject withHttpType:@"POST" withTag:SX_SX_queryGrouponProject];
    
}

#pragma mark == 店铺代金劵
- (void)getStoreSalePaper{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_foodId forKey:@"storeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryFoodsVoucher withHttpType:@"POST" withTag:SX_SX_queryFoodsVoucher];
    
}

#pragma mark == 分享
- (IBAction)shareHandel:(id)sender {
    SharePopView * popView = [[SharePopView alloc]initWithTitles:@[@"微信好友",@"朋友圈",@"新浪微博",@"QQ好友"] complect:^(NSInteger index) {
        switch (index) {
            case 0:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
                
            }
                break;
            case 1:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            case 2:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToSina] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            case 3:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            default:
                break;
        }

    }];
    [popView show];
}


#pragma mark == 获取商家评论
- (void)getComments{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_foodId forKey:@"storeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppMallGrouponCommentByStoreId withHttpType:@"POST" withTag:SX_SX_queryAppMallGrouponCommentByStoreId];
    
}

#pragma mark == 查看全部评论
- (IBAction)showAllComment:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    AllMovieCommentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AllMovieComment"];
    page.commentId = _foodId;
    page.type = 3;
    [self.navigationController   pushViewController:page animated:YES];
}
#pragma mark == 商家相册
- (IBAction)photos:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    PhotosViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Photos"];
    page.imagesArray = _imageArray;
    [self.navigationController   pushViewController:page animated:YES];
}

#pragma mark == 拨打电话
- (IBAction)callHandel:(id)sender {
    [Common callPhone:_storePhone.text view:self.view];
}
#pragma mark == 跳转代金卷
- (IBAction)getForSalePaper:(id)sender {
    if (_pricePaperArray.count>0) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        PaperListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PaperList"];
        page.paperArray = _pricePaperArray ;
        [self.navigationController   pushViewController:page animated:YES];
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        ForSalePaperViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ForSalePaper"];
        [self.navigationController   pushViewController:page animated:YES];
    }
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _commentTableView) {
        CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
        return height ;
    }else{
        return 72*VerticalRatio();
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != _commentTableView) {
        FoodsStoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify ];
        if (cell==nil) {
            cell = [[FoodsStoreTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];
            
        }
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSDictionary * dic = _groupShops[indexPath.row];
        cell.shopName.frame = flexibleFrame(CGRectMake(115, 13, 197, 0), NO);
        cell.shopName.text = [NSString stringWithFormat:@"%@",dic[@"mgprName"]];
        [cell.shopName sizeToFit];
        
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mgimPhoneImg"]];
        if (image.length>0) {
            [cell.shopImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }
        NSString *mgpiGourponAmount = @"";
        if (![dic[@"mgpiGourponAmount"] isEqual:[NSNull null]]) {
            mgpiGourponAmount = dic[@"mgpiGourponAmount"];
        }
        cell.shopPrice.text = [NSString stringWithFormat:@"¥%@",mgpiGourponAmount];
        NSString *mgpiOrginalAmount = @"";
        if (![dic[@"mgpiOrginalAmount"] isEqual:[NSNull null]]) {
            mgpiOrginalAmount = dic[@"mgpiOrginalAmount"];
        }
        
        return cell;
    }else{
        MovieCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify ];
        if (cell == nil) {
            cell = [[MovieCommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        NSDictionary * dic = _commitArray[indexPath.row];
        NSString * image = dic[@"memberImg"];
        if (image) {
            [cell.headImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            cell.headImage.image = [UIImage imageNamed:@"comment1"];
        }
        double star = [[NSString stringWithFormat:@"%.1f",[dic[@"mgcoCommentStars"]floatValue ]/2]doubleValue];
        
        CommitStarsView * stars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(13, 50, 80, 15), NO) Stars:star];
        [cell addSubview:stars];
        
        cell.commentInfo.frame = flexibleFrame(CGRectMake(10, 72, 300, 15), YES);
        cell.commentInfo.numberOfLines = 0;
        cell.commentInfo.text = dic[@"mgcoContent"];
        [cell.commentInfo sizeToFit];
        
        cell.name.text = dic[@"mgcoAuthor"];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[dic[@"commentDate"] integerValue]/1000];
        cell.date.text = [formatter stringFromDate:confromTimesp];
        
        
        return cell;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView != _commentTableView) {
        return _groupShops.count;
    }else{
        if (_commitArray.count<=2) {
            return _commitArray.count;
        }else{
            return 2;
        }
    }
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    
    if (tag==SX_SX_queryAppBusinessDetailsInfo) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _imageArray = database[@"result"][@"list"];
            _imageNumber.text = [NSString stringWithFormat:@"%ld",_imageArray.count];
            
            NSDictionary * dic = database[@"result"];
            NSString * image  = [NSString stringWithFormat:@"%@",self.imageName];
            if (image.length>0) {
                [_storeBackImage sd_setImageWithURL:[NSURL URLWithString:image]];
                [_storeLogoImage sd_setImageWithURL:[NSURL URLWithString:self.imageBrandName]];
                _storeLogoImage.layer.masksToBounds = YES;
                _storeLogoImage.layer.cornerRadius = 28;
            }
            _storeName.text = [NSString stringWithFormat:@"%@",dic[@"storeName"]];
            NSString *storeType = dic[@"storeType"];
            if ([dic[@"storeType"] isEqual:[NSNull null]]) {
                storeType = @"中餐";
            }
            _storeIntroduce.text = [NSString stringWithFormat:@"%@  人均:¥%@",storeType,dic[@"msgoPerConsumption"]];
            
            double start = [[NSString stringWithFormat:@"%.1f",[dic[@"storeCommAvg"]floatValue]/2] doubleValue];
            CommitStarsView * CommentStars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(65, 123, 80, 15), NO) Stars:start];
            [_scroView addSubview:CommentStars];
            _storeScore.text = [NSString stringWithFormat:@"%.1f分",start];
            _commentScore.text = [NSString stringWithFormat:@"%.1f分",start];
            _workTime.text = [NSString stringWithFormat:@"%@:%@-%@:%@",dic[@"msgoBeginHour"],dic[@"msgoBeignMinute"],dic[@"msgoEndHour"],dic[@"msgoEndMinute"]];
            _storeAddress.text = [NSString stringWithFormat:@"%@",dic[@"storeAddress"]];
            _storePhone.text = [NSString stringWithFormat:@"%@",dic[@"storePhone"]];
            
        }
    }else if (tag == SX_SX_queryFoodsVoucher){
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _pricePaperArray = database[@"result"][@"pageRecord"];
            if (_pricePaperArray.count>0) {
                NSDictionary * dic = _pricePaperArray[0];
                _storeForSale.text = [NSString stringWithFormat:@"%@",dic[@"mgprName"]];
                _storePrice.text = [NSString stringWithFormat:@"¥%@ 门市价：¥%@",dic[@"mgpiGourponAmount"],dic[@"mgpiOrginalAmount"]];
                _hadSale.text = [NSString stringWithFormat:@"已售%@",dic[@"mgprSelledcount"]];
            }else{
                
            }
            
            
        }
        
    }else if (tag == SX_SX_queryAppMallGrouponCommentByStoreId){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _commitArray = database[@"result"];
            _commentTotalNum.text = [NSString stringWithFormat:@"评价（%ld）",_commitArray.count];
            if (_commitArray.count==0) {
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), _scroView.contentSize.height-250*VerticalRatio());
            }else if (_commitArray.count==1){
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), _scroView.contentSize.height-125*VerticalRatio());
            }
            if (_scroView.contentSize.height<=kDeviceHeight) {
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), 569*VerticalRatio());
            }
            for (int i = 0; i<_commitArray.count; i++) {
                NSString * commentImage = _commitArray[i][@"mgciImag"];
                NSString * comment = _commitArray[i][@"mgcoContent"];
                NSInteger height = 0;
                if (commentImage.length==0 ) {
                    height = 90;
                }else{
                    height = 130;
                }
                
                
                int lines = 0;
                CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                lines = cSize.width/300*VerticalRatio() + 1 ;
                
                height  += lines * 17;
                
                [_heightArray addObject:@(height)];
            }
            _commentTableView.delegate = self;
            _commentTableView.dataSource = self;
            [_commentTableView reloadData];
            
        }
        
    }else if (tag == SX_SX_queryGrouponProject){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _groupShops = database[@"result"][@"pageRecord"];
            _foodsTableView.dataSource = self;
            _foodsTableView.delegate = self;
            [_foodsTableView reloadData];
            if (_groupShops.count==0) {
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), CGRectGetMaxY(_commentTableView.frame));
            }else if (_groupShops.count==1){
                _foodsTableView.frame = flexibleFrame(CGRectMake(0, 352, 320, 177-72), NO);
                _commentLineLabel.frame = CGRectMake(0,CGRectGetMaxY(_foodsTableView.frame) , 320*VerticalRatio(), 5*VerticalRatio());
                _gotoCmmentPageButton.frame = CGRectMake(0,(536-72)*VerticalRatio() , 308*VerticalRatio(), 32*VerticalRatio());
                _commentTotalNum.frame = CGRectMake(15*VerticalRatio(),(534-72)*VerticalRatio() , 90*VerticalRatio(), 35*VerticalRatio());
                _commentScore.frame = CGRectMake(265*VerticalRatio(),(541-72)*VerticalRatio() , 42*VerticalRatio(), 21*VerticalRatio());
                
                _commentTableView.frame = CGRectMake(0,CGRectGetMaxY(_commentTotalNum.frame) , 320*VerticalRatio(), CGRectGetHeight(_commentTableView.frame));
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), CGRectGetMaxY(_commentTableView.frame));
            }
            if (_scroView.contentSize.height<=kDeviceHeight) {
                _scroView.contentSize = CGSizeMake(0*VerticalRatio(), 569*VerticalRatio());
            }
        }
        
        
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
